/*
 * Copyright 2002-2006 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package blms.services.internal;

import java.io.Serializable;
import java.util.Date;

import blms.domain.League;
import blms.domain.Match;
import blms.domain.User;
import blms.exception.MatchDoesNotExistException;
import blms.exception.ValidationException;
import blms.repository.MatchRepository;
import blms.services.MatchService;
import blms.util.BLMSMessages;

/**
 * Default implementation of <code>MatchService</code>.
 * 
 * @author Jonhnny Weslley
 * @version 1.00, 22/04/2008
 * @since 1.0
 */

public class MatchServiceImpl implements MatchService {

	private final MatchRepository matches;

	/**
	 * @param matches
	 */
	public MatchServiceImpl(final MatchRepository matches) {
		this.matches = matches;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.services.MatchService#createMatch(blms.domain.League,
	 *      blms.domain.User, blms.domain.User, java.util.Date, int, int, int,
	 *      int)
	 */
	public Match createMatch(final League league, final User winner,
			final User loser, final Date date, final int length,
			final int score, final int longestRunForWinner,
			final int longestRunForLoser) throws ValidationException {

		final Match match = new Match.Builder(league).winner(winner,
				longestRunForWinner).loser(loser, longestRunForLoser)
				.withScore(score).withLength(length).on(date);

		match.validate();
		matches.add(match);
		return match;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.services.MatchService#getMatch(java.io.Serializable)
	 */
	public Match getMatch(final Serializable id)
			throws MatchDoesNotExistException {

		if (!matches.contains(id)) {
			throw new MatchDoesNotExistException(
					BLMSMessages.UNKNOWN_MATCH_MESSAGE);
		}
		return matches.get(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.services.MatchService#updateMatch(blms.domain.Match,
	 *      blms.domain.Match)
	 */
	public void updateMatch(final Match match) throws ValidationException {
		match.validate();
		matches.update(match);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.services.MatchService#deleteMatch(java.io.Serializable)
	 */
	public void deleteMatch(final Serializable id)
			throws MatchDoesNotExistException {

		final Match match = getMatch(id);
		matches.remove(match);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.services.MatchService#removeAllMatches()
	 */
	public void removeAllMatches() {
		matches.removeAll();
	}

}